package com.yb.personelmanagement.service.system;

import com.yb.personelmanagement.domain.System.Result;
import com.yb.personelmanagement.domain.System.StatusCode;
import com.yb.personelmanagement.domain.System.User;
import com.yb.personelmanagement.domain.System.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

/**
 * @Auther: lzx
 * @Date: 2019/8/8 10:52
 * @Description:
 */
@Service
public class UserServiceImpl implements  UserService {
    @Autowired
    UserRepository userRepository;
    @Override
    public Result findAllUser() {
        List<User> userList=userRepository.findAll();
        return new Result(true,userList,"查询成功",StatusCode.SUCCESS);
    }
	@Override
	public Result addUser(User user) {
		User user1=userRepository.save(user);
		if(null!=user1)
		return new Result(true,user1,"保存成功",StatusCode.SUCCESS);
		else
			return new Result(false,user1,user.toString(),StatusCode.PARAM_ERROR_JSON);
	}
	@Override
	public Result findById(Long id) {
		User user1=userRepository.findById(id).get();
		
		return new Result(true,user1,"查询成功",StatusCode.SUCCESS);
		
	}
	
	
	private Specification<User> createSpecification(Map searchMap){
		return new Specification<User>() {
		@Override
		public Predicate toPredicate(Root<User> root, CriteriaQuery<?>
		criteriaQuery, CriteriaBuilder cb) {
		List<Predicate> predicateList=new ArrayList<>();
		if(searchMap.get("username")!=null &&
		!"".equals(searchMap.get("username"))){
		predicateList.add(cb.like(
		root.get("username").as(String.class), "%"+
		(String)searchMap.get("username")+"%" ) );
		}
		
		return cb.and( predicateList.toArray( new
		Predicate[predicateList.size()]) );
		}
		};
		}
	
	public List<User> findSearch(Map searchMap){
		Specification specification= createSpecification(searchMap);
		return userRepository.findAll( specification);
		}
	
	public Page<User> findSearch(Map searchMap,int page,int size){
		Specification specification= createSpecification(searchMap);
		PageRequest pageRequest=PageRequest.of(page-1,size);
		return userRepository.findAll(specification ,pageRequest);
		}
	
	 
}
